package com.yzh;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author 于振晗
 * @title: TestDome4j03
 * @description: TODO DOM4j插入一条数据
 * @date 2020年09月08日
 * @path com.yzh
 */
public class TestDom4j03 {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        File file = new File("Java_Xml/student1.xml");
        Document doc = reader.read(file);
        //获取文档的根节点
        Element rootElement = doc.getRootElement();
        List<Element> list = rootElement.elements();

        //向根节点加入一个子节点   student
        Element student = DocumentHelper.createDocument().addElement("student");
        //为子节点添加一个属性    id
        student.addAttribute("id", "S222");
        //为子节点添加一些子节点   name    age
        Element name = student.addElement("name");
        //为子节点文本赋值
        name.setText("小三");
        Element age = student.addElement("age");
        age.setText(">80");
        list.add(1,student);

        OutputFormat outputFormat =OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(file),outputFormat);
        xmlWriter.write(doc);
        xmlWriter.close();
    }
}
